/*
 * Copyright (c) 2015, 张涛.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tiantian.quanminxiu.utils.face;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.shenglian.utils.utils.CommonUtils;
import com.tiantian.quanminxiu.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 控件主界面
 *
 * @author kymjs (http://www.kymjs.com/)
 */
public class KJChatKeyboard extends RelativeLayout implements
        SoftKeyboardStateHelper.SoftKeyboardStateListener {

    public interface OnToolBoxListener {
        void onShowFace();
    }

    public static final int LAYOUT_TYPE_HIDE = 0;
    public static final int LAYOUT_TYPE_FACE = 1;
    public static final int LAYOUT_TYPE_MORE = 2;


    public static final int MSG_CHAT = 0;
    public static final int MSG_FLY = 1;
    public static final int MSG_HORN = 2;
    public static final int MSG_TOLDHIM = 3;
    public static final int MSG_PRIVATE = 4;



    public int MessageType = MSG_CHAT;
    public int User_ID;
    private String UserName;

    private View linRootView;

    /**
     * 最上层输入框
     */
    private EditText mEtMsg;
    private ImageView mBtnFace,imgChatType;
    private Button mBtnSend;

    /**
     * 表情
     */
    private RelativeLayout mRlFace;

    private int layoutType = LAYOUT_TYPE_HIDE;

    private List<String> mFaceData;

    private Context context;
    private SoftKeyboardStateHelper mKeyboardHelper;

    private GridView gl;
    private FaceAdapter adapter;
    private List<FaceModel>list;

    public KJChatKeyboard(Context context) {
        super(context);
        init(context);
    }

    public KJChatKeyboard(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public KJChatKeyboard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        View root = View.inflate(context, R.layout.chat_tool_box, null);
        this.addView(root);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initData();
        this.initWidget();
    }

    private void initData() {
//        mKeyboardHelper = new SoftKeyboardStateHelper(((Activity) getContext())
//                .getWindow().getDecorView());
//        mKeyboardHelper.addSoftKeyboardStateListener(this);
    }

    //region 初始化控件 initWidget
    private void initWidget() {
        linRootView = findViewById(R.id.linRootView);
        mEtMsg = (EditText) findViewById(R.id.toolbox_et_message);
        mBtnSend = (Button) findViewById(R.id.toolbox_btn_send);
        mBtnFace = (ImageView) findViewById(R.id.toolbox_btn_face);
        imgChatType = (ImageView) findViewById(R.id.imgChatType);
        mRlFace = (RelativeLayout) findViewById(R.id.toolbox_layout_face);
        gl = (GridView) findViewById(R.id.gl);
        list = new ArrayList<FaceModel>();
        initFaces();
        adapter = new FaceAdapter(context, list);
        gl.setAdapter(adapter);
        gl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mEtMsg.append(list.get(position).getFacetext());
            }
        });
        imgChatType.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageType = (MessageType+1)%3;
                setMessageType();
            }
        });
        mBtnSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sendMessageListener != null) {
                    String content = mEtMsg.getText().toString();
                    if (content.isEmpty()){
                        CommonUtils.showToask(context,"不能发送为空..");
                        return;
                    }
                    switch (MessageType){
                        case MSG_CHAT:
                            sendMessageListener.sendChatMessage("Message", content);
                            break;
                        case MSG_TOLDHIM:
                            sendMessageListener.sendChatMessage("Message",User_ID, content,false);
                            break;
                        case MSG_PRIVATE:
                            sendMessageListener.sendChatMessage("Message",User_ID, content,true);
                            break;
                        case MSG_HORN:
                            sendMessageListener.sendChatMessage("Horn","SERVER", content);
                            break;
                        case MSG_FLY:
                            sendMessageListener.sendChatMessage("Horn","ROOM", content);
                            break;
                    }
                    mEtMsg.setText(null);
                }
            }
        });
        // 点击表情按钮
        mBtnFace.setOnClickListener(OC_FaceTOKey);
        // 点击表情按钮旁边的加号
        // 点击消息输入框
        mEtMsg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hideLayout();
            }
        });
        setMessageType();
    }//endregion

    //region 输入框KJChatKeyboard显示 setShow() setHide() isShow()
    public void setShow(){
        linRootView.setVisibility(View.VISIBLE);
    }
    public void setHide(){
        linRootView.setVisibility(View.GONE);
    }
    public boolean isShow(){
        return (linRootView.getVisibility()==View.VISIBLE);
    }
    //endregion

    //region 改变消息类型 setMessageType
    public void setMessageType(){
        switch (MessageType){
            case MSG_CHAT:
                imgChatType.setImageResource(R.drawable.icon_kjchat_chat);
                mEtMsg.setHint("请输入聊天文字");
                break;
            case MSG_TOLDHIM:
                imgChatType.setImageResource(R.drawable.icon_kjchat_chat);
                mEtMsg.setHint("@对"+UserName+"说");
                break;
            case MSG_PRIVATE:
                imgChatType.setImageResource(R.drawable.icon_kjchat_chat);
                mEtMsg.setHint("@对"+UserName+"悄悄说");
                break;
            case MSG_FLY:
                imgChatType.setImageResource(R.drawable.icon_kjchat_fly);
                mEtMsg.setHint("飞屏消息(2000币/条)");
                break;
            case MSG_HORN:
                imgChatType.setImageResource(R.drawable.icon_kjchat_horn);
                mEtMsg.setHint("全服喇叭(5000币/条)");
                break;
        }
    }
    //endregion

    public void setMessageType(int type){
        MessageType = type;
        setMessageType();
    };
    public void setMessageType(int type,int user_ID,String userName){
        this.UserName = userName;
        this.User_ID = user_ID;
        setMessageType(type);
    };

    //region getVisibility
    @Override
    public int getVisibility() {
        return super.getVisibility();
    }
    //endregion

    //region 初始化表情图片
    public void initFaces() {

        // 必须按从小到大的顺序加 聊天适配器要判断表情
        // 普通表情 从1到56，数字不能变
        for (int i = 1; i < 19; i++) {
            String facetext = "[f" + i + "]";
            String facename = "emoji_" + i;
            int faceId = getResources().getIdentifier("emoji_" + i, "drawable", context.getPackageName());

            FaceModel faceModel = new FaceModel(faceId, facename,
                    facetext);
            list.add(faceModel);
        }
    }
    //endregion

    //region 点击表情 OC_FaceTOKey
    public OnClickListener OC_FaceTOKey = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("oc","--onclick:"+layoutType);
            if (isFaceShow() && layoutType==LAYOUT_TYPE_HIDE) {
                hideLayout();
                showKeyboard(context);
                layoutType = LAYOUT_TYPE_FACE;
            } else {
                layoutType = LAYOUT_TYPE_HIDE;
                showLayout();
                mBtnFace.setImageResource(R.drawable.icon_keyboard_nor);
            }
        }
    };
    //endregion

    //region onSoftKeyboardOpened onSoftKeyboardClosed
    @Override
    public void onSoftKeyboardOpened(int keyboardHeightInPx) {
        hideLayout();
    }

    @Override
    public void onSoftKeyboardClosed() {
    }
    //endregion

    //region 展示表情列表 showLayout
    public void showLayout() {
        hideKeyboard(this.context);
        // 延迟一会，让键盘先隐藏再显示表情键盘，否则会有一瞬间表情键盘和软键盘同时显示
        postDelayed(new Runnable() {
            @Override
            public void run() {
                mRlFace.setVisibility(View.VISIBLE);
//                if (mFaceListener != null) {
//                    mFaceListener.onShowFace();
//                }
            }
        }, 50);
    }
    //endregion

    //region 表情列表是否展示 isFaceShow
    public boolean isFaceShow() {
        return mRlFace.getVisibility() == VISIBLE;
    }
    //endregion

    //region 隐藏表情列表 hideLayout
    public void hideLayout() {
        mRlFace.setVisibility(View.GONE);
        mBtnFace.setImageResource(R.drawable.icon_face);
    }
    //endregion

    //region 隐藏软键盘 hideKeyboard
    public void hideKeyboard(Context context) {
        Activity activity = (Activity) context;
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive() && activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus()
                        .getWindowToken(), 0);
            }
        }
    }
    //endregion

    //region 显示软键盘 showKeyboard
    public void showKeyboard(Context context) {
        Activity activity = (Activity) context;
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInputFromInputMethod(activity.getCurrentFocus()
                    .getWindowToken(), 0);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
        mEtMsg.setFocusable(true);
        mEtMsg.setFocusableInTouchMode(true);
        mEtMsg.requestFocus();
    }
    //endregion

    //region 设置发送消息回调 sendMessageListener
    public SendMessageListener sendMessageListener;
    public interface SendMessageListener{
        void sendChatMessage(String type,String content);
        void sendChatMessage(String type,int User_ID,String content,boolean pre);
        void sendChatMessage(String type,String horn,String content);
    }
    public void setSendMessageListener(SendMessageListener sendMessageListener){
        this.sendMessageListener = sendMessageListener;
    };
    public SendMessageListener getSendMessageListener(){
        return sendMessageListener;
    };
    //endregion

}